package com.mdd.admin.service.log.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mdd.admin.service.log.IOrderLogService;
import com.mdd.admin.service.user.IUserService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.log.OrderLogParam;
import com.mdd.admin.vo.log.OrderLogDetailVo;
import com.mdd.admin.vo.log.OrderLogListVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.log.OrderLog;
import com.mdd.common.enums.OperateEnum;
import com.mdd.common.mapper.log.OrderLogMapper;
import com.mdd.common.utils.TimeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单日志实现类
 */
@Service
public class OrderLogServiceImpl extends ServiceImpl<OrderLogMapper, OrderLog> implements IOrderLogService {

    @Resource
    OrderLogMapper orderLogMapper;

    @Resource
    private IUserService userService;

    /**
     * 订单日志列表
     *
     * @param pageParam 分页参数
     * @param params    搜索参数
     * @return PageResult<OrderLogListVo>
     */
    @Override
    public PageResult<OrderLogListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        QueryWrapper<OrderLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        orderLogMapper.setSearch(queryWrapper, params, new String[]{
                "=:type:int",
                "=:channel:int",
                "=:orderId@order_id:int",
                "=:operatorId@operator_id:int",
                "=:content:str",
        });

        IPage<OrderLog> iPage = orderLogMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<OrderLogListVo> list = new LinkedList<>();
        for (OrderLog item : iPage.getRecords()) {
            OrderLogListVo vo = new OrderLogListVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 订单日志详情
     *
     * @param id 主键参数
     * @return OrderLog
     */
    @Override
    public OrderLogDetailVo detail(Integer id) {
        OrderLog model = orderLogMapper.selectOne(
                new QueryWrapper<OrderLog>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        OrderLogDetailVo vo = new OrderLogDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 订单日志新增
     *
     * @param orderLogParam 参数
     */
    @Override
    public void add(OrderLogParam orderLogParam) {
        OrderLog model = new OrderLog();
        model.setType(orderLogParam.getType());
        model.setChannel(orderLogParam.getChannel());
        model.setOrderId(orderLogParam.getOrderId());
        model.setOperatorId(orderLogParam.getOperatorId());
        model.setContent(orderLogParam.getContent());
        orderLogMapper.insert(model);
    }

    /**
     * 订单日志编辑
     *
     * @param orderLogParam 参数
     */
    @Override
    public void edit(OrderLogParam orderLogParam) {
        OrderLog model = orderLogMapper.selectOne(
                new QueryWrapper<OrderLog>()
                        .eq("id", orderLogParam.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(orderLogParam.getId());
        model.setType(orderLogParam.getType());
        model.setChannel(orderLogParam.getChannel());
        model.setOrderId(orderLogParam.getOrderId());
        model.setOperatorId(orderLogParam.getOperatorId());
        model.setContent(orderLogParam.getContent());
        orderLogMapper.updateById(model);
    }

    /**
     * 订单日志删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        OrderLog model = orderLogMapper.selectOne(
                new QueryWrapper<OrderLog>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        orderLogMapper.delete(new QueryWrapper<OrderLog>().eq("id", id));
    }

    @Override
    public List<OrderLogDetailVo> listByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderLog::getOrderId, orderId);
        lambdaQueryWrapper.orderByAsc(OrderLog::getCreateTime);
        List<OrderLog> logList = orderLogMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(logList)) {
            return Lists.newArrayList();
        }
        List<Long> userIds = logList.stream()
                .filter(x -> x.getType() == OperateEnum.TYPE_USER.getType())
                .map(OrderLog::getOperatorId)
                .distinct().collect(Collectors.toList());
        Map<Integer, String> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(item -> item.getId(), item -> item.getNickname(), (a, b) -> b));
        List<OrderLogDetailVo> targetList = Lists.newArrayList();
        for (OrderLog orderLog : logList) {
            OrderLogDetailVo vo = new OrderLogDetailVo();
            BeanUtils.copyProperties(orderLog, vo);
            int operatorId = orderLog.getOperatorId().intValue();
            if (OperateEnum.TYPE_SYSTEM.getType() == orderLog.getType()){
                vo.setOperatorName(OperateEnum.TYPE_SYSTEM.getDesc());
            }
            if (OperateEnum.TYPE_ADMIN.getType() == orderLog.getType()){
                vo.setOperatorName(OperateEnum.TYPE_ADMIN.getDesc());
            }
            if (OperateEnum.TYPE_USER.getType() == orderLog.getType()){
                if (userMap.containsKey(operatorId)) {
                    vo.setOperatorName(userMap.get(operatorId));
                }
            }
            vo.setOperateTime(TimeUtil.timestampToDate(orderLog.getCreateTime()));
            targetList.add(vo);
        }
        return targetList;
    }

    @Override
    public void saveEntity(OrderLog orderLog) {
        super.save(orderLog);
    }

}
